#!/usr/bin/env python
# Create: 2018/11/6
__author__ = '749B'
"""修改节点名称
根据IP查找节点，获取uri
向uri提交，修改NodeName
"""

import requests

from sds.swis_login import swis


def get_uri_by_ip(ip_addr, node_name):
    results = swis.query("SELECT Uri, NodeName FROM Orion.Nodes WHERE IP=@ip_addr", ip_addr=ip_addr)
    # 确保只查到1个结果
    if len(results['results']) == 0:
        print(ip_addr, "未查询到任何节点")
        return
    elif len(results['results']) > 1:
        print(ip_addr, "查询到多个节点: ", results['results'])
        return
    _node_name = results['results'][0]['NodeName']
    if node_name == _node_name:
        print("NodeName 相同，无需修改:", ip_addr, node_name)
        return
    # print("找到节点:", node_name)
    return results['results'][0]['Uri']


def update_node_name(uri, node_name):
    if not uri:
        return
    uri = uri + '/'
    resp = swis.update(uri, NodeName=node_name)
    if resp:
        print("Update返回异常:", resp)
    return resp


def run(ip_addr, node_name):
    uri = get_uri_by_ip(ip_addr, node_name)
    if not uri:
        return
    print("\r提交修改:", ip_addr, node_name, end='\t', flush=True)
    resp = update_node_name(uri, node_name)
    return resp


requests.packages.urllib3.disable_warnings()


if __name__ == '__main__':
    run("192.168.201.1", "TEST1")
